<form id="addOrUpdateForm" lay-filter="addOrUpdateForm" class="layui-form model-form">

    <div class="layui-col-md6">
        <input name="testpaperId" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">问卷名称</label>
            <div class="layui-input-block">
                <input name="title" class="layui-input" placeholder="请输入问卷名称" lay-verType="tips" lay-verify="required"
                       required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">问卷说明</label>
            <div class="layui-input-block">
                <input name="remarks" class="layui-input" placeholder="请输入问卷说明" lay-verType="tips" lay-verify="required"
                       required/>
            </div>
        </div>
    </div>

    <div class="layui-col-md6">
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">问卷类型</label>
            <div class="layui-input-block">
                <input name="papertype" class="layui-input" placeholder="请输入问卷类型" lay-verType="tips"
                       lay-verify="required" required/>
            </div>
        </div>
    </div>
    <!--<div class="layui-form-item">
        <label class="layui-form-label">问卷对象</label>
        <div class="layui-input-block">
            <div id="examinee"></div>
        </div>
    </div>-->

    <div class="layui-form-item" id="defineDataTreeBox">
        <label class="layui-form-label">授权数据</label>
        <div class="layui-input-block" style="max-height: 190px;overflow: auto">
            <ul id="grantOrgTree" class="ztree"></ul>
        </div>
    </div>

    <!--<div class="layui-form-item">
        <label class="layui-form-label">问卷人员</label>
        <div class="layui-input-block">
            <div id="personnel"></div>
            &lt;!&ndash;<input name="personnel" id="personnel" class="layui-input" style="float: left;width: 823px"
                   placeholder="请输入问卷人员" lay-verType="tips" disabled="disabled"/>
            <input name="personnelid" id="personnelId" style="display: none"/>
            <button type="button" id="choosePerson" class="layui-btn layui-btn-sm icon-btn"
                    style="height:35px;padding-left: 10px;margin-left: 2px"><i class="layui-icon">&#xe654;</i></button>&ndash;&gt;
        </div>
    </div>-->


    <div class="layui-col-md12">
        <div class="layui-form-item">
            <label class="layui-form-label">附属信息</label>
            <button class="layui-btn layui-btn-sm icon-btn" id="extAddButton" type="button">
                <i class="layui-icon">&#xe654;</i>添加问卷
            </button>
            <div class="layui-input-block">
                <table id="extTable" lay-filter="extTable"></table>
            </div>
        </div>
    </div>

    <div class="layui-form-item text-right">
        <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        <button class="layui-btn" lay-filter="formSubmitBtn" lay-submit>保存</button>
    </div>
</form>
<!--<style>
    .theme-colorful .layui-input-block {
        max-height: 190px;
        overflow: auto;
    }
</style>-->
<script type="text/html" id="extTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" perm-show="testpaper:edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" perm-show="testpaper:delete" lay-event="delete">删除</a>
</script>
<script>
    layui.use(['layer', 'form', 'admin', 'xnUtil', 'tableX', 'xmSelect', 'laydate', 'table', 'zTree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var xnUtil = layui.xnUtil;
        var tableX = layui.tableX;
        var xmSelect = layui.xmSelect;
        var laydate = layui.laydate;
        var table = layui.table;

        var extTableData = [];
        var insExtTb = tableX.render({
            elem: '#extTable',
            data: [],
            page: false,
            defaultToolbar: [],
            cellMinWidth: 100,
            cols: [
                [
                    {field: 'testpapermxId', hide: true},
                    {field: 'numbers', title: '序号', align: 'center', type: 'numbers'},
                    {field: 'title', title: '大题题目'},
                    {
                        field: 'type', title: '题型', templet: function (d) {
                            if (d.type == 0) {
                                return "单选";
                            } else if (d.type == 1) {
                                return "多选";
                            } else if (d.type == 2) {
                                return "判断";
                            } else if (d.type == 3) {
                                return "填空";
                            } else if (d.type == 4) {
                                return "问答";
                            }
                        }
                    },
                    {field: 'total', title: '题总数'},
                    {field: 'remark', title: '备注'},
                    {title: '操作', toolbar: '#extTableBar', align: 'center', width: 400, minWidth: 200}
                ]
            ],
            done: function (res, curr, count) {
                xnUtil.tableDone(insExtTb, res, curr, count);
            }
        });

        var editData = admin.getLayerData('#addOrUpdateForm').data;
        debugger;
        if (editData !== null && editData !== undefined) {
            form.val('addOrUpdateForm', editData);
            admin.req(getProjectUrl() + 'testpaper/detail?testpaperId=' + editData.testpaperId, function (res) {
                //重载表格
                debugger;
                extTableData = res.data;
                insExtTb.reload({data: extTableData});
            });
        }

        $("#choosePerson").click(function () {
            var layIndex = admin.open({
                offset: '0px',
                title: "用户信息",
                area: ['850px', '520px'],
                url: getProjectUrl() + 'testpaper/userInfo',
                data: {},     // 传递数据到表单页面
                end: function () {
                    debugger;
                    var layerData = admin.getLayerData(layIndex, 'formOk');
                    if (layerData) {  // 判断表单操作成功标识
                        debugger;
                        var resultData = admin.getLayerData(layIndex, 'resultData');
                        var personal = "";
                        var personnelId = "";
                        for (var i = 0; i < resultData.length; i++) {
                            personal = personal + resultData[i].name + ";";
                            personnelId = personnelId + resultData[i].id + ";";
                        }
                        $("#personnel").val(personal);
                        $("#personnelId").val(personnelId)
                    }
                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    $(layero).find('[lay-submit]').focus();
                }
            });
        })


        // 获取机构树
        admin.req(getProjectUrl() + 'sysOrg/tree', function(res){
            // 渲染树
            debugger;
            var zTree = $.fn.zTree.init($('#grantOrgTree'), {
                check: {enable: true, chkboxType: {"Y": "s", "N": "s" }},
                data: {
                    key: {name: 'title'},
                    simpleData: {enable: true, rootPId: 0}
                }
            }, xnUtil.handleNoChildrenZtreeData(xnUtil.handleZtreeDataOpen(res.data)));

            // 获取已授权的机构id集合
            /*admin.req(getProjectUrl() + 'sysUser/ownData?id=' + grantData.id, function(res){
                // 设置默认选择
                res.data.forEach(function (value) {
                    zTree.checkNode(zTree.getNodeByParam( "id", value), true);
                })
            });*/
            if(editData !== null && editData !== undefined){
                var personnelid = editData.personnelid;
                var personArr = personnelid.split(";");
                personArr.forEach(function (value) {
                    zTree.checkNode(zTree.getNodeByParam( "id", value), true);
                })
            }

        });
        /**
         * 表单提交事件
         */
        form.on('submit(formSubmitBtn)', function (data) {
            debugger;
            layer.load(2);
            var url = editData ? getProjectUrl() + 'testpaper/edit' : getProjectUrl() + 'testpaper/add';
            var extIds = [];
            extTableData.forEach(function (value) {
                var tempObj = {};
                tempObj.title = value.title;
                tempObj.total = value.total;
                tempObj.type = value.type;
                if (value.selectedtopics == undefined || value.selectedtopics == "") {
                    var selectEdTopics = "";
                    value.selectData.forEach(function (val) {
                        selectEdTopics += val.id + ",";
                    });
                    selectEdTopics.slice(0, -1);
                    tempObj.selectedtopics = selectEdTopics;
                } else {
                    tempObj.selectedtopics = value.selectedtopics;
                }
                extIds.push(tempObj);
            })
            /*data.field.examinee = data.field.grantRoleIdList;*/
            data.field.testpapermxList = extIds;
            var grantOrgIdList = [];
            $.fn.zTree.getZTreeObj("grantOrgTree").getCheckedNodes(true).forEach(function (value) {
                grantOrgIdList.push(value.id);
            });
            data.field.grantOrgIdList = grantOrgIdList;
            admin.req(url, JSON.stringify(data.field), function (res) {
                layer.msg(res.message, {icon: 1, time: 1000}, function () {
                    admin.putLayerData('formOk', true, '#addOrUpdateForm');
                    admin.closeDialog('#addOrUpdateForm');
                });
            }, 'post');
            return false;
        });
        /* 添加附属信息点击事件 */
        $('#extAddButton').click(function () {
            showExtOrgPosAddOrUpdateModel();
        });

        // 显示表单弹窗
        function showExtOrgPosAddOrUpdateModel(data) {
            var layIndex = admin.open({
                offset: '0px',
                title: (data ? '修改' : '添加') + '问卷',
                area: ['850px', '520px'],
                url: getProjectUrl() + 'testpaper/extForm',
                data: {data: data},     // 传递数据到表单页面
                end: function () {
                    var layerData = admin.getLayerData(layIndex, 'formOk');
                    if (layerData) {  // 判断表单操作成功标识
                        var resultData = admin.getLayerData(layIndex, 'resultData');
                        if (data) {
                            for (var i = 0; i < extTableData.length; i++) {
                                if (extTableData[i].orgId === data.orgId && extTableData[i].posId === data.posId) {
                                    extTableData.splice(i, 1, resultData);
                                }
                            }
                        } else {
                            extTableData.push(resultData);
                        }

                        insExtTb.reload({data: extTableData}); // 成功刷新表格
                    }
                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    $(layero).find('[lay-submit]').focus();
                }
            });
        }

        table.on('tool(extTable)', function (obj) {
            if (obj.event === 'edit') {
                showExtOrgPosAddOrUpdateModel(obj.data);
            }
            if (obj.event === 'delete') {
                layer.confirm('确定要操作该数据吗？', {
                    skin: 'layui-layer-admin',
                    shade: .1
                }, function (index) {
                    debugger;
                    for (var i = 0; i < extTableData.length; i++) {
                        if (extTableData[i].testpapermxId === obj.data.testpapermxId) {
                            extTableData.splice(i, 1);
                        }
                    }
                    insExtTb.reload({data: extTableData});
                    /* obj.del();*/
                    layer.close(index);
                });
            }
        });

        // 渲染远程数据下拉
        // 渲染远程数据下拉
        //var grantRoleRenderIns = {};
        var selectData1;
        var userData;
        admin.req(getProjectUrl() + 'sysRole/dropDown', function (res) {
            debugger;
            selectData1 = res.data;
        }, {async: false});
        var grantRoleRenderIns = xmSelect.render({
            el: '#examinee',
            name: 'grantRoleIdList',
            data: selectData1,
            tree:{
                show:true,
                expandedKeys:[1]
            },
            toolbar: {
                show: true
            },
            filterable: true,
            paging: true,
            pageSize: 10,
            radio: false,
            linkage: true,
            prop: {
                name: 'name',
                value: 'id'
            },
            model: {
                label: {
                    type: 'block',
                    block: {
                        //最大显示数量, 0:不限制
                        showCount: 3
                    }
                }
            },
            on: function (data) {
                debugger;
                var arras = data.arr;
                var roles = "";
                for(var i = 0;i < arras.length;i++){
                    roles += arras[i].id+";";
                }
                getUserInfo(roles);
                var grantUserRenderIns = xmSelect.render({
                    el: '#personnel',
                    name: 'grantUserIdList',
                    data: userData,
                    toolbar: {
                        show: true
                    },
                    filterable: true,
                    paging: true,
                    pageSize: 10,
                    radio: false,
                    filterable: true,
                    prop: {
                        name: 'name',
                        value: 'id'
                    },
                    model: {
                        label: {
                            type: 'block',
                            block: {
                                //最大显示数量, 0:不限制
                                showCount: 8
                            }
                        }
                    },
                    tips: '请选择用户'
                });
            },
            tips: '请选择角色'
        });

        getUserInfo("");
        function getUserInfo(vals) {
            admin.req(getProjectUrl() + 'sysRole/dropUserDown?name='+vals,function (res) {
                userData = res.data;
            }, {async: false});
        }

        // 渲染远程数据下拉

        var grantUserRenderIns = xmSelect.render({
            el: '#personnel',
            name: 'grantUserIdList',
            data: userData,
            toolbar: {
                show: true
            },
            filterable: true,
            paging: true,
            pageSize: 10,
            radio: false,
            filterable: true,
            prop: {
                name: 'name',
                value: 'id'
            },
            model: {
                label: {
                    type: 'block',
                    block: {
                        //最大显示数量, 0:不限制
                        showCount: 8
                    }
                }
            },
            tips: '请选择用户'
        });
        if (editData !== null && editData !== undefined) {
            debugger;
            /*var arrs = [];
            var arrs1 = [];
            arrs.push(editData.examinee);
            arrs1.push(editData.personelid)*/
            grantRoleRenderIns.setValue(editData.examinee.split(","));
            grantUserRenderIns.setValue(editData.personnelid.split(";"));
        }
    });
</script>
</body>
</html>
